﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DefaultScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;
using EmployeeCustomersScope;

namespace Klient.Forms
{
    public partial class MyCustomers : PhoneApplicationPage
    {
        #region Dependency Property
        public static DependencyProperty AllCustomersProperty = DependencyProperty.Register(
            "AllCustomers", typeof(ObservableCollection<Customers>), typeof(MyCustomers), null);
        public ObservableCollection<Customers> AllCustomers
        {
            get
            {
                return (ObservableCollection<Customers>)GetValue(AllCustomersProperty);
            }
            set
            {
                SetValue(AllCustomersProperty, value);
            }
        }
        #endregion

        EmployeeCustomersScopeOfflineContext customerContext;
        bool isCacheOpen = false;
        bool isCacheBusy = false;
        private string customerID;

        public MyCustomers()
        {
            DataContext = this;

            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            NavigationContext.QueryString.TryGetValue("customerID", out customerID);

            customerContext = new EmployeeCustomersScopeOfflineContext("customers" + customerID, new Uri("http://localhost:4000/EmployeeCustomersScopeSyncService.svc/"));
            
            customerContext.CacheController.ControllerBehavior.AddScopeParameters("customerID", customerID);

            customerContext.CacheController.ControllerBehavior.SerializationFormat = Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;
            customerContext.CacheController.RefreshCompleted += new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(CacheController_RefreshCompleted);
            customerContext.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(context_LoadCompleted);
            
            this.Loaded += new RoutedEventHandler(MyCustomers_Loaded);

            isCacheOpen = true;
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (isCacheBusy)
            {
                e.Cancel = true;
                return;
            }
            isCacheOpen = false;
            customerContext.Close();
            base.OnNavigatingFrom(e);
        }

        void MyCustomers_Loaded(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen & !isCacheBusy)
            {
                progressBar.Visibility = Visibility.Collapsed;
                try
                {
                    customerContext.LoadAsync();
                }
                catch (ObjectDisposedException)
                {
                    /* ignore - sometimes happens that page is closed so quickly that context from which
                    * becomes disposed but it is not a problem, the page
                    * content do not interests us anyway after we left the page
                    */
                };
            }
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                delegate
                {
                    if (isCacheOpen)
                    {
                        progressBar.Visibility = Visibility.Collapsed;
                        AllCustomers = new ObservableCollection<Customers>(
                            customerContext.CustomersCollection);
                    }
                }
);
        }

        void CacheController_RefreshCompleted(object sender, Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            isCacheBusy = false;
            progressBar.Visibility = Visibility.Collapsed;
            AllCustomers = new ObservableCollection<Customers>(
                        customerContext.CustomersCollection);
            if (e.Error != null)
                Dispatcher.BeginInvoke(delegate { MessageBox.Show(e.Error.ToString()); });
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!customerContext.CacheController.IsBusy)
            {
                if (isCacheOpen & !isCacheBusy)
                {
                    isCacheBusy = true;
                    progressBar.Visibility = Visibility.Visible;
                    customerContext.SaveChanges();
                    customerContext.CacheController.RefreshAsync();
                }
            }
        }
    }
}